import mongoose from 'mongoose';
import { UserPermissionDAO } from '../dao/UserPermissionDAO';
import { OrganizationDAO } from '../dao/OrganizationDAO';
import { SystemDAO } from '../dao/SystemDAO';
import { UserDAO } from '../dao/UserDAO';
import { PermissionDAO } from '../dao/PermissionDAO';
import { IUser } from '../models/user';
import { IPermission } from '../models/permission';
import { ISystemDocument } from '../models/system';

/**
 * 集成服务
 * 处理系统间的集成和数据同步
 */
export class IntegrationService {
  private userPermissionDAO: UserPermissionDAO;
  private organizationDAO: OrganizationDAO;
  private systemDAO: SystemDAO;
  private userDAO: UserDAO;
  private permissionDAO: PermissionDAO;

  constructor() {
    this.userPermissionDAO = new UserPermissionDAO();
    this.organizationDAO = new OrganizationDAO();
    this.systemDAO = new SystemDAO();
    this.userDAO = new UserDAO();
    this.permissionDAO = new PermissionDAO();
  }

  /**
   * 获取用户权限信息
   * @param userId 用户ID
   * @param systemId 系统ID
   * @returns 用户权限信息
   */
  async getUserPermissionInfo(userId: mongoose.Types.ObjectId, systemId: mongoose.Types.ObjectId): Promise<{
    success: boolean;
    message: string;
    data?: {
      userId: mongoose.Types.ObjectId;
      permissions: IPermission[];
      roles: string[];
      systemInfo: any;
    };
  }> {
    // 验证系统是否存在
    const system = await this.systemDAO.findById(systemId);
    if (!system) {
      throw new Error('系统不存在');
    }

    // 验证用户是否存在
    const user = await this.userDAO.findById(userId);
    if (!user) {
      throw new Error('用户不存在');
    }

    try {

      // 获取用户权限
      const userPermissions = await this.userPermissionDAO.getUserPermissions(userId);

      return {
        success: true,
        message: '获取用户权限信息成功',
        data: {
          userId,
          permissions: userPermissions.permissions,
          roles: userPermissions.roles,
          systemInfo: {
            systemCode: system.systemCode,
            systemName: system.systemName
          }
        }
      };
    } catch (error) {
      return {
        success: false,
        message: `获取用户权限信息失败: ${error}`
      };
    }
  }

  /**
   * 批量获取用户权限
   * @param userIds 用户ID数组
   * @param systemId 系统ID
   * @returns 批量用户权限信息
   */
  async batchGetUserPermissions(userIds: mongoose.Types.ObjectId[], systemId: mongoose.Types.ObjectId): Promise<{
    success: boolean;
    message: string;
    data?: {
      systemId: mongoose.Types.ObjectId;
      userPermissions: Record<string, any>;
      totalCount: number;
    };
  }> {
    // 验证用户ID列表不能为空
    if (!userIds || userIds.length === 0) {
      throw new Error('用户ID列表不能为空');
    }

    // 验证系统是否存在
    const system = await this.systemDAO.findById(systemId);
    if (!system) {
      return {
        success: false,
        message: '系统不存在'
      };
    }

    // 验证用户是否存在
    for (const userId of userIds) {
      const user = await this.userDAO.findById(userId);
      if (!user) {
        throw new Error('无效的用户ID');
      }
    }

    try {
      // 批量获取用户权限
      const userPermissions = await this.userPermissionDAO.batchGetUserPermissions(userIds);

      return {
        success: true,
        message: '批量获取用户权限成功',
        data: {
          systemId,
          userPermissions,
          totalCount: userIds.length
        }
      };
    } catch (error) {
      return {
        success: false,
        message: `批量获取用户权限失败: ${error}`
      };
    }
  }

  /**
   * 获取组织用户
   * @param organizationQuery 组织查询条件
   * @param systemId 系统ID
   * @returns 组织用户信息
   */
  async getOrganizationUsers(organizationQuery: {
    teamId?: mongoose.Types.ObjectId;
    departmentId?: mongoose.Types.ObjectId;
    groupId?: mongoose.Types.ObjectId;
  }, systemId: mongoose.Types.ObjectId): Promise<{
    success: boolean;
    message: string;
    data?: {
      organizationId: mongoose.Types.ObjectId;
      users: Array<{
        userId: mongoose.Types.ObjectId;
        username: string;
        realName: string;
        email: string;
      }>;
      totalCount: number;
    };
  }> {
    // 验证系统是否存在
    const system = await this.systemDAO.findById(systemId);
    if (!system) {
      return {
        success: false,
        message: '系统不存在'
      };
    }

    const organizationId = organizationQuery.teamId || organizationQuery.departmentId || organizationQuery.groupId;
    if (!organizationId) {
      return {
        success: false,
        message: '组织ID不能为空'
      };
    }

    // 验证组织是否存在
    let organizationExists = false;
    if (organizationQuery.teamId) {
      const team = await mongoose.connection.db?.collection('teams').findOne({ _id: organizationQuery.teamId });
      organizationExists = !!team;
    } else if (organizationQuery.departmentId) {
      const department = await mongoose.connection.db?.collection('departments').findOne({ _id: organizationQuery.departmentId });
      organizationExists = !!department;
    } else if (organizationQuery.groupId) {
      const group = await mongoose.connection.db?.collection('groups').findOne({ _id: organizationQuery.groupId });
      organizationExists = !!group;
    }

    if (!organizationExists) {
      throw new Error('组织不存在');
    }

    try {
      // 获取组织用户
      const users = await this.organizationDAO.getOrganizationUsers(organizationQuery);

      return {
        success: true,
        message: '获取组织用户成功',
        data: {
          organizationId,
          users: users.map(user => ({
            userId: user._id as mongoose.Types.ObjectId,
            username: user.username,
            realName: user.realName,
            email: user.email
          })),
          totalCount: users.length
        }
      };
    } catch (error) {
      return {
        success: false,
        message: `获取组织用户失败: ${error}`
      };
    }
  }

  /**
   * 处理权限回调
   * @param callbackData 回调数据
   * @param systemId 系统ID
   * @returns 处理结果
   */
  async handlePermissionCallback(callbackData: {
    userId: mongoose.Types.ObjectId;
    action: 'grant' | 'revoke';
    permissions: mongoose.Types.ObjectId[];
  }, systemId: mongoose.Types.ObjectId): Promise<{
    success: boolean;
    message: string;
    data?: {
      userId: mongoose.Types.ObjectId;
      action: string;
      processedPermissions: number;
    };
  }> {
    try {
      // 验证系统是否存在
      const system = await this.systemDAO.findById(systemId);
      if (!system) {
        return {
          success: false,
          message: '系统不存在'
        };
      }

      // 验证用户是否存在
      const user = await this.userDAO.findById(callbackData.userId);
      if (!user) {
        return {
          success: false,
          message: '用户不存在'
        };
      }

      // 这里应该实现具体的权限授予或撤销逻辑
      // 由于没有具体的权限分配表，这里只是模拟处理
      
      return {
        success: true,
        message: '权限变更回调处理成功',
        data: {
          userId: callbackData.userId,
          action: callbackData.action,
          processedPermissions: callbackData.permissions.length
        }
      };
    } catch (error) {
      return {
        success: false,
        message: `处理权限回调失败: ${error}`
      };
    }
  }

  /**
   * 同步用户信息
   * @param syncData 同步数据
   * @param systemId 系统ID
   * @returns 同步结果
   */
  async syncUserInfo(syncData: {
    userId: string;
    userData: {
      realName?: string;
      phone?: string;
      status?: number;
      email?: string;
      username?: string;
    };
    operatorId: string;
    timestamp: Date;
  }, systemId: mongoose.Types.ObjectId): Promise<{
    success: boolean;
    message: string;
    data?: {
      userId: mongoose.Types.ObjectId;
      syncedFields: string[];
      syncTime: Date;
    };
  }> {
    // 验证系统是否存在
    const system = await this.systemDAO.findById(systemId);
    if (!system) {
      return {
        success: false,
        message: '系统不存在'
      };
    }

    // 验证用户是否存在
    const userId = new mongoose.Types.ObjectId(syncData.userId);
    const user = await this.userDAO.findById(userId);
    if (!user) {
      throw new Error('用户不存在');
    }

    try {

      // 准备更新数据
      const updateData: any = {};
      const syncedFields: string[] = [];

      if (syncData.userData.realName) {
        updateData.realName = syncData.userData.realName;
        syncedFields.push('realName');
      }
      if (syncData.userData.phone) {
        updateData.phone = syncData.userData.phone;
        syncedFields.push('phone');
      }
      if (syncData.userData.email) {
        updateData.email = syncData.userData.email;
        syncedFields.push('email');
      }
      if (syncData.userData.username) {
        updateData.username = syncData.userData.username;
        syncedFields.push('username');
      }
      if (syncData.userData.status !== undefined) {
        updateData.status = syncData.userData.status === 1 ? 'active' : 'inactive';
        syncedFields.push('status');
      }

      // 更新用户信息
      if (Object.keys(updateData).length > 0) {
        await this.userDAO.update(userId, updateData);
      }

      return {
        success: true,
        message: '用户信息同步成功',
        data: {
          userId,
          syncedFields,
          syncTime: new Date()
        }
      };
    } catch (error) {
      return {
        success: false,
        message: `用户信息同步失败: ${error}`
      };
    }
  }

  /**
   * 同步组织信息
   * @param organizationData 组织数据
   * @param systemId 系统ID
   * @returns 同步结果
   */
  async syncOrganizationInfo(organizationData: {
    teamId?: mongoose.Types.ObjectId;
    departmentId?: mongoose.Types.ObjectId;
    groupId?: mongoose.Types.ObjectId;
  }, systemId: mongoose.Types.ObjectId): Promise<{
    success: boolean;
    message: string;
    data?: {
      organizationData: any;
      syncedEntities: string[];
      syncTime: Date;
    };
  }> {
    try {
      // 验证系统是否存在
      const system = await this.systemDAO.findById(systemId);
      if (!system) {
        return {
          success: false,
          message: '系统不存在'
        };
      }

      // 这里应该实现具体的组织信息同步逻辑
      const syncedEntities: string[] = [];
      
      if (organizationData.teamId) {
        syncedEntities.push('team');
      }
      if (organizationData.departmentId) {
        syncedEntities.push('department');
      }
      if (organizationData.groupId) {
        syncedEntities.push('group');
      }

      return {
        success: true,
        message: '组织信息同步成功',
        data: {
          organizationData,
          syncedEntities,
          syncTime: new Date()
        }
      };
    } catch (error) {
      return {
        success: false,
        message: `组织信息同步失败: ${error}`
      };
    }
  }
}

export default IntegrationService;